package Controller;

import Interface.User.User;
import Interface.Admin.zhujiemian;
import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Font;
import javafx.stage.Stage;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class Client extends Application {
    private Socket clientSocket;
    public PrintWriter out;
    public BufferedReader in;
    private TextField t_name;
    private PasswordField p_password ;
    // 静态变量，用于保存当前用户的Client对象引用
    static Client currentClient;
    private Stage primaryStage;
    public static String id;
    public  String number ="2";//选择框
    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
        showMainWindow();
    }
    private void showMainWindow(){
        Label l_name=new Label("账号:");
        l_name.setFont(Font.font(14));

        Label l_password=new Label("密码:");
        l_password.setFont(Font.font(14));

        t_name =new TextField();
        p_password = new PasswordField();

        Button login =new Button("登录");
        login.setOnAction(e -> login());
        Button clear =new Button("注册");
        clear.setOnAction(e -> clear());

        ToggleGroup group = new ToggleGroup();//管理，一次选一个
        RadioButton guanli = new RadioButton("管理员");
        RadioButton yonghu = new RadioButton("用户");
        guanli.setToggleGroup(group);
        yonghu.setToggleGroup(group);
        yonghu.setSelected(true);

        guanli.setUserData("1");
        yonghu.setUserData("2");

        group.selectedToggleProperty().addListener( (ObservableValue<? extends Toggle > observable, Toggle oldValue, Toggle newValue)->{
            if (group.getSelectedToggle() != null) {
                //System.out.println(group.getSelectedToggle().getUserData().toString());
                number=group.getSelectedToggle().getUserData().toString();
            }
        } );

        FileInputStream input= null;
        try {
            input = new FileInputStream("C:\\Users\\86178\\Videos\\0150585c9c9098a801208f8bf252f5.jpg@1280w_1l_2o_100sh.jpg");
        } catch (FileNotFoundException e) {
            System.out.println("图像打开失败");
        }
        Image image = new Image(input);
        ImageView imageView =new ImageView(image);
        imageView.setFitWidth(488);
        imageView.setFitHeight(465);

        Pane pane = new Pane();
        pane.getChildren().add(imageView);
        pane.getChildren().addAll(l_name,l_password,t_name,p_password,login,clear,guanli,yonghu);

        l_name.setLayoutX(180);
        l_name.setLayoutY(122);

        l_password.setLayoutX(180);
        l_password.setLayoutY(162);

        t_name.setLayoutX(220);
        t_name.setLayoutY(120);

        p_password.setLayoutX(220);
        p_password.setLayoutY(160);

        login.setLayoutX(340);
        login.setLayoutY(230);

        clear.setLayoutX(220);
        clear.setLayoutY(230);

        guanli.setLayoutX(220);
        guanli.setLayoutY(200);

        yonghu.setLayoutX(300);
        yonghu.setLayoutY(200);


        Scene scene =new Scene(pane);
        primaryStage.setScene(scene);
        primaryStage.setTitle("健身房管理系统");
        primaryStage.setWidth(500);
        primaryStage.setHeight(500);
        primaryStage.setResizable(false);//窗口不可拉伸
        primaryStage.show();

        try {
            clientSocket =new Socket("127.0.0.1",8888);
            out=new PrintWriter(clientSocket.getOutputStream(), true);
            in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            System.out.println("服务端连接成功");
        } catch (Exception e) {
            System.out.println("服务端连接失败");
        }
    }

    void sendMessageToServer(String message) {
        try {
            out.println(message);
            System.out.println(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class AccountGenerator {
        public static String generateAccount() {
            // 使用 UUID 生成一个随机的账号
            return UUID.randomUUID().toString();
        }
    }

    private void clear() {//注册
        Label l_password=new Label("密码:");
        Label r_password=new Label("确认密码:");
        l_password.setFont(Font.font(14));//设置字体大小

        PasswordField p_password = new PasswordField();
        PasswordField r1_password = new PasswordField();
        GridPane gridPane=new GridPane();
        gridPane.setStyle("-fx-background-color:rgb(238,232,232)");//背景
        gridPane.add(l_password,0,1);
        gridPane.add(r_password,0,2);
        gridPane.add(r1_password,1,1);
        gridPane.add(p_password,1,2);

        gridPane.setHgap(5);//水平间距
        gridPane.setVgap(17);//垂直间距

        gridPane.setAlignment(Pos.CENTER);//所有元素居中

        Scene scene =new Scene(gridPane);
        Stage stage=new Stage();
        stage.setScene(scene);
        stage.setTitle("注册");
        stage.setWidth(500);
        stage.setHeight(500);
        stage.show();

        Button login =new Button("确定");
        gridPane.add(login,1,3);
        GridPane.setMargin(login,new Insets(0,0,0,50));//单独设置间距

        login.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                if (p_password.getText().equals(r1_password.getText())) {
                    String username = AccountGenerator.generateAccount();
                    String password = p_password.getText();

                    // 发送注册请求给服务端
                    if(out!=null) {
                        out.println("注册");
                        out.println(username);
                        out.println(password);
                        try {
                            // 接收服务端的响应
                            String response = in.readLine();
                            if (response.equals("注册成功")) {
                                stage.setTitle("注册成功!");
                                stage.close();
                                Label word=new Label("您的账号是："+username);
                                GridPane gridPane=new GridPane();
                                gridPane.setStyle("-fx-background-color:rgb(238,232,232)");//背景
                                gridPane.add(word,0,1);
                                Scene scene1 =new Scene(gridPane);
                                Stage stage1=new Stage();
                                stage1.setScene(scene1);
                                stage1.setTitle("注册成功");
                                stage1.setWidth(500);
                                stage1.setHeight(500);
                                stage1.show();
                            } else {
                                stage.setTitle("注册失败!");
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    stage.setTitle("密码不一致！");
                    p_password.clear();
                    r1_password.clear();
                }
            }
        });

    }

    private void login() {//登录
        String username = t_name.getText();
        String password = p_password.getText();

        if(number.equals("2"))  {
            User user =new User();
            try {
                user.start(new Stage());
                id=t_name.getText();
                primaryStage.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        // 发送登录请求给服务端
        out.println("登录");
        out.println(username);
        out.println(password);
        try {
            // 接收服务端的响应
            String response = in.readLine();
            if (response.equals("登录成功")) {
                System.out.println("登录成功!");
                zhujiemian zhujiemian =new zhujiemian();
                try {
                    id=t_name.getText();
                    zhujiemian.start(new Stage());

                    // 登录成功后，将当前用户的Client对象引用赋值给currentClient
                    currentClient = this;
                    primaryStage.close();
                } catch (Exception e) {
                    System.out.println("主界面打开失败");
                }
            } else {
                System.out.println("登录失败!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
